package com.netease.nim.uikit.business.session.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netease.nim.uikit.R;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.api.model.contact.ContactChangedObserver;
import com.netease.nim.uikit.api.model.main.OnlineStateChangeObserver;
import com.netease.nim.uikit.api.model.session.SessionCustomization;
import com.netease.nim.uikit.api.model.user.UserInfoObserver;
import com.netease.nim.uikit.business.preference.UserPreferences;
import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.business.session.fragment.MessageFragment;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nim.uikit.common.MyConst;
import com.netease.nim.uikit.common.http.NimHttpClient;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 点对点聊天界面
 */
public class P2PMessageActivity extends BaseMessageActivity implements View.OnClickListener{

    private boolean isResume = false;
    private TextView tv_buddy_name;
    public static void start(Context context, String contactId, SessionCustomization customization, IMMessage anchor) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);
        if (anchor != null) {
            intent.putExtra(Extras.EXTRA_ANCHOR, anchor);
        }
        intent.setClass(context, P2PMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        context.startActivity(intent);
    }

    @Override
    public boolean isTransStatusBar() {
        return true;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.nim_message_activity;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        // 单聊特例话数据，包括个人信息，
        requestBuddyInfo();
        displayOnlineState();
        registerObservers(true);
        registerOnlineStateChangeListener(true);
        requestVisitorInfoById();
    }

    private void initView() {
        tv_buddy_name = findView(R.id.tv_buddy_name);
        findView(R.id.iv_back).setOnClickListener(this);

        findView(R.id.iv_add_info).setOnClickListener(this);

        findView(R.id.iv_view_detail).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.iv_back) {
            finish();
        } else if (i == R.id.iv_add_info) {
            if(mLanchListener!=null){
                mLanchListener.startAddInfoActivity(sessionId);
            }
        }else if(i==R.id.iv_view_detail){
            if(mLanchListener!=null){
                mLanchListener.startViewInfoActivity(visitorInfoContent,sessionId);
            }
        }
    }
    private static ILanchListener mLanchListener;
    public static void setLanchListener(ILanchListener lanchListener){
        mLanchListener = lanchListener;
    }

    public interface ILanchListener{
        void startAddInfoActivity(String sessionId);
        void startViewInfoActivity(String sessionId, String id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        registerObservers(false);
        registerOnlineStateChangeListener(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    private void requestBuddyInfo() {
        setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));

    }

    private void setTitle(String name){
        tv_buddy_name.setText(name);
    }

    private void registerObservers(boolean register) {
        if (register) {
            registerUserInfoObserver();
        } else {
            unregisterUserInfoObserver();
        }
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(commandObserver, register);
        NimUIKit.getContactChangedObservable().registerObserver(friendDataChangedObserver, register);
    }

    ContactChangedObserver friendDataChangedObserver = new ContactChangedObserver() {
        @Override
        public void onAddedOrUpdatedFriends(List<String> accounts) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onDeletedFriends(List<String> accounts) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onAddUserToBlackList(List<String> account) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onRemoveUserFromBlackList(List<String> account) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }
    };

    private UserInfoObserver uinfoObserver;

    OnlineStateChangeObserver onlineStateChangeObserver = new OnlineStateChangeObserver() {
        @Override
        public void onlineStateChange(Set<String> accounts) {
            // 更新 toolbar
            if (accounts.contains(sessionId)) {
                // 按照交互来展示
                displayOnlineState();
            }
        }
    };

    private void registerOnlineStateChangeListener(boolean register) {
        if (!NimUIKitImpl.enableOnlineState()) {
            return;
        }
        NimUIKitImpl.getOnlineStateChangeObservable().registerOnlineStateChangeListeners(onlineStateChangeObserver, register);
    }

    private void displayOnlineState() {
        if (!NimUIKitImpl.enableOnlineState()) {
            return;
        }
        String detailContent = NimUIKitImpl.getOnlineStateContentProvider().getDetailDisplay(sessionId);
        //setSubTitle(detailContent);TODO 设置在状态信息
    }

    private void registerUserInfoObserver() {
        if (uinfoObserver == null) {
            uinfoObserver = new UserInfoObserver() {
                @Override
                public void onUserInfoChanged(List<String> accounts) {
                    if (accounts.contains(sessionId)) {
                        requestBuddyInfo();
                    }
                }
            };
        }
        NimUIKit.getUserInfoObservable().registerObserver(uinfoObserver, true);
    }

    private void unregisterUserInfoObserver() {
        if (uinfoObserver != null) {
            NimUIKit.getUserInfoObservable().registerObserver(uinfoObserver, false);
        }
    }

    /**
     * 命令消息接收观察者
     */
    Observer<CustomNotification> commandObserver = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification message) {
            if (!sessionId.equals(message.getSessionId()) || message.getSessionType() != SessionTypeEnum.P2P) {
                return;
            }
            showCommandMessage(message);
        }
    };

    private String visitorInfoContent="";
    protected void showCommandMessage(CustomNotification message) {
        if (!isResume) {
            return;
        }

        String content = message.getContent();
        try {
            JSONObject json = JSON.parseObject(content);
            int id = json.getIntValue("id");
            if (id == 1) {
                // 正在输入
                Toast.makeText(P2PMessageActivity.this, "对方正在输入...", Toast.LENGTH_LONG).show();
            } else {
                visitorInfoContent = content;
                /*LogUtil.i("wjk",content);
                JSONObject jsonObject = JSONObject.parseObject(content);
                JSONObject result = jsonObject.getJSONObject("xUserInfo").getJSONObject("baseinfo");
                String visitorId = result.getString("visitorId");
                if(visitorId!=null){
                    requestVisitorInfoById(visitorId,result);
                    UserPreferences.saveString(visitorId,result.toJSONString());
                }
                Toast.makeText(P2PMessageActivity.this, "command: " + content, Toast.LENGTH_SHORT).show();*/
            }
        } catch (Exception e) {

        }
    }

    private void requestVisitorInfoById() {

        NimUserInfo user = NIMClient.getService(UserService.class).getUserInfo(sessionId);
        if(user==null){
            return;
        }
        Map<String, Object> extensionMap = user.getExtensionMap();
        final String visitorId = (String) extensionMap.get("visitorId");

        NimHttpClient.getInstance().init(this);
        Map<String, String> headers = new HashMap<>(1);
        headers.put("Content-Type","application/x-www-form-urlencoded");
        StringBuilder body = new StringBuilder();
        SharedPreferences preferences = NimUIKit.getContext().getSharedPreferences("Demo", Context.MODE_PRIVATE);
        body.append("visitorId").append("=").append(visitorId).append("&")
                .append("enterpriseId").append("=").append(preferences.getString("orgId",null));
        String bodyString = body.toString();
        NimHttpClient.getInstance().execute(MyConst.GET_VISITOR_INFO, headers, bodyString,
                true, new NimHttpClient.NimHttpCallback() {
                    @Override
                    public void onResponse(String response, int code, Throwable exception) {
                        if(code==200){
                            JSONObject obj = JSONObject.parseObject(response);
                            UserPreferences.saveString(visitorId,response);
                            /*result.put("receptionServer",obj.getString("receptionServer"));
                            result.put("visitorChatCount",obj.getString("visitorChatCount"));
                            result.put("haveChat",obj.getString("haveChat"));
                            result.put("remark",obj.getString("remark"));
                            result.put("ipLocation",obj.getString("ipLocation"));
                            result.put("ipAddress",obj.getString("ipAddress"));
                            result.put("firstVisitorAddress",obj.getString("firstVisitorAddress"));*/
                        }
                    }
                });
//        {
//            "acctId": "5ed155eb07ae4fe4b2853b604c50bad9",
//                "browser": "chrome",
//                "browserVersion": "60.0.3112.113",
//                "createTime": "2018-05-18 14:51:34.0",
//                "enterpriseId": "10171",
//                "firstVisitorAddress": "http://alastroy.ru/solution.html",
//                "haveChat": "1",
//                "ipAddress": "103.65.40.69",
//                "ipLocation": "香港",
//                "lang": "zh-CN",
//                "leaveTime": "2018-05-18 14:52:51",
//                "osInfo": "Windows",
//                "receptionServer": "王芳",
//                "remark": "",
//                "screenColorDepth": "24",
//                "screenResolution": "1920*1080",
//                "serverChatCount": "1",
//                "timezone": "GTM+08:00",
//                "title": "Варианты решения",
//                "visitorChatCount": "3",
//                "visitorId": "10171FK20180518145134791",
//                "visitorName": "香港5",
//                "visitorType": ""
//        }
    }

    @Override
    protected MessageFragment fragment() {
        Bundle arguments = getIntent().getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.P2P);
        MessageFragment fragment = new MessageFragment();
        fragment.setArguments(arguments);
        fragment.setContainerId(R.id.message_fragment_container);
        return fragment;
    }

    @Override
    protected void initToolBar() {
        //ToolBarOptions options = new NimToolBarOptions();
        //setToolBar(R.id.toolbar, options);
    }
}
